﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Event.UI;
using CPPEI.Coolzon.Theme;
using CPPEI.Coolzon.Theme.Default;
using CPPEI.Coolzon.Theme.Events;
using CPPEI.Coolzon.UI;
using CPPEI.Coolzon.UI.Event;
using CPPEI.Coolzon.UI.Views;
using CPPEI.Coolzon.UI.Views.Windows;
using CPPEI.WPF.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.ConsoleApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string _userAccount;
        private string _userPassword;

        private View _mainView;
        private XWindowHelper _fullScreenHelper;

        private DisableInteractiveWindow _disableInteractiveWindow;

        private object _lockLoadingView = new object();

        public MainWindow()
        {
            InitializeComponent();

            this.Title = string.Format("控制器-v{0}", CZEnvironment.Version4);

            #region 设置窗口的全屏状态
            _fullScreenHelper = new XWindowHelper(this);
            if (CZEnvironment.Instance.IsFullScreen)
            {
                _fullScreenHelper.EnterFullscreen();
                UIContext.Current.IsFullScreen = true;
            }
            else
            {
                _fullScreenHelper.ExitFullscreen();
                UIContext.Current.IsFullScreen = false;
            }
            #endregion

            Common.EventBus.Instance.Register(this);
            UIEventBus.Register(this);

            Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Register(this);
            Common.EventBus.Create(CPPEI.Coolzon.Theme.Events.EventBusFlag.APPUI).Register(this);

            // 注册到事件总线
            Common.EventBus.Instance.Register(RemoteEventProxy.Instance);
            NCLEventBus.Register(RemoteEventProxy.Instance);
            Event.Core.CoreEventBus.Register(RemoteEventProxy.Instance);

            UIContext.Current.RootViewContainer = _ctlViewContainer;

            CPPEI.Coolzon.UI.Views.LoginView loginView;
            if (CZEnvironment.Instance.LoginMode.ToUpper().Equals("WINDOWS"))
            {
                loginView = new UI.Views.LoginView(Environment.UserName, "");
            }
            else
            {
                loginView = new UI.Views.LoginView();
            }
            loginView.Close += loginView_Close;
            UIContext.Current.RootViewContainer.SwitchView(loginView);
            loginView.Active();
        }

        void loginView_Close(UI.View view, bool isCancel)
        {
            if (!isCancel)
            {
                //HB:只心跳不同步状态
                HeartbeatThread.Start(HeartbeatThreadWorkMode.KeepAlive);

                CPPEI.Coolzon.UI.Views.LoginView loginView = view as UI.Views.LoginView;
                _userAccount = loginView.UserAccount;
                _userPassword = loginView.UserPassword;

                // 显示选择方案的界面
                if (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() is Coolvis.Console.Theme.IThemeV2)
                {
                    CPPEI.Coolzon.UI.View selectSolutionView = (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() as Coolvis.Console.Theme.IThemeV2).CreateSelectSolutionView("", false, false);
                    selectSolutionView.Close += selectSolutionView_Close;
                    _ctlViewContainer.SwitchSubView(selectSolutionView);
                    selectSolutionView.Active();
                }
                else
                {
                    CPPEI.Coolzon.UI.View selectSolutionView = new UI.Views.SelectSolutionView();
                    selectSolutionView.Close += selectSolutionView_Close;
                    _ctlViewContainer.SwitchSubView(selectSolutionView);
                    selectSolutionView.Active();
                }
            }
        }

        void selectSolutionView_Close(UI.View view, bool isCancel)
        {
            if (!isCancel)
            {
                CPPEI.Coolzon.UI.Views.ISelectSolutionView selectSolutionView = view as UI.Views.ISelectSolutionView;

                if (selectSolutionView.IsNewDomain)
                {
                    UIContext.Current.IsEnterDomainByCreate = true;
                }
                else
                {
                    UIContext.Current.IsEnterDomainByCreate = false;
                }

                // 进入方案加载界面，停止重新建立连接的线程
                ReconnectThread.Stop();

                if (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() is Coolvis.Console.Theme.IThemeV2)
                {
                    CPPEI.Coolzon.UI.View loadingView = (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() as Coolvis.Console.Theme.IThemeV2).CreateLoadingView(selectSolutionView.SelectedSolutionName,
                        CZEnvironment.GetSolutionFilePath(selectSolutionView.SelectedSolutionName),
                        CZEnvironment.GetSolutionDirectoryPath(selectSolutionView.SelectedSolutionName));
                    loadingView.Close += OnLoadingViewClose;
                    (loadingView as CPPEI.Coolzon.UI.Views.ILoadingView).LoadSolutionErrorEvent += LoadingView_LoadSolutionErrorEvent;
                    _ctlViewContainer.SwitchView(loadingView);
                    loadingView.Active();
                }
                else
                {
                    CPPEI.Coolzon.UI.Views.LoadingView loadingView = new UI.Views.LoadingView(selectSolutionView.SelectedSolutionName,
                        CZEnvironment.GetSolutionFilePath(selectSolutionView.SelectedSolutionName),
                        CZEnvironment.GetSolutionDirectoryPath(selectSolutionView.SelectedSolutionName));
                    loadingView.Close += OnLoadingViewClose;
                    loadingView.LoadSolutionErrorEvent += LoadingView_LoadSolutionErrorEvent;
                    _ctlViewContainer.SwitchView(loadingView);
                    loadingView.Active();
                }
            }
        }
        /// <summary>
        /// 加载方案出错事件
        /// </summary>
        /// <param name="errorMessage"></param>
        private void LoadingView_LoadSolutionErrorEvent(string errorMessage)
        {
            //控制端提示错误信息
            System.Windows.MessageBox.Show(errorMessage);

            // 显示选择方案的界面
            if (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() is Coolvis.Console.Theme.IThemeV2)
            {
                CPPEI.Coolzon.UI.View selectSolutionView = (CPPEI.Coolzon.Theme.ThemeManager.GetCurrentThemeInst() as Coolvis.Console.Theme.IThemeV2).CreateSelectSolutionView("", true, false);
                selectSolutionView.Close += selectSolutionView_Close;
                _ctlViewContainer.SwitchSubView(selectSolutionView);
                selectSolutionView.Active();
            }
            else
            {
                CPPEI.Coolzon.UI.View selectSolutionView = new UI.Views.SelectSolutionView("", true, false);
                selectSolutionView.Close += selectSolutionView_Close;
                _ctlViewContainer.SwitchSubView(selectSolutionView);
                selectSolutionView.Active();
            }
        }
        /// <summary>
        /// 加载方案窗口关闭事件
        /// </summary>
        /// <param name="view"></param>
        /// <param name="isCancel"></param>
        private void OnLoadingViewClose(UI.View view, bool isCancel)
        {
            //方案加载完毕之后再启动重新建立连接的线程
            ReconnectThread.Start();
            //方案加载完毕之后，现在开启切换主服务的线程，决定哪一个服务器作为主服务器。
            SwitchMainServerThread.Start();

            UI.Views.LoadingView loadingView = view as UI.Views.LoadingView;

            _mainView = (View)ThemeManager.CreateThemeInstance(ThemeManager.GetCurrentTheme()).GetMainView();
            _ctlViewContainer.SwitchView(_mainView);
            _mainView.Active();

            //正在加载方案设置成false
            UIContext.Current.IsLoadingSolution = false;

            //通知服务器已恢复正常状态
            Coolzon.Event.NCL.NCLUpdateClientStatusEvent @eventNormal = new Coolzon.Event.NCL.NCLUpdateClientStatusEvent(Service.Contract.ClientStatus.Normal);
            Coolzon.Event.NCL.NCLEventBus.Publish(@eventNormal);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (_ctlViewContainer.CurrentView != null)
            {
                _ctlViewContainer.CurrentView.Destory();
            }

            Common.EventBus.Instance.Unregister(RemoteEventProxy.Instance);
            Common.EventBus.Create(CPPEI.Coolzon.Theme.Events.EventBusFlag.APPUI).Unregister(this);
            UIEventBus.Unregister(this);

            //关闭提示信息窗口
            if (hintView != null)
            {
                hintView.Close();
                hintView = null;
            }
            HeartbeatThread.Stop();
            ReconnectThread.Stop();
            SwitchMainServerThread.Stop();
            OpenDefaultSceneThread.Stop();
            CheckClientStatusThread.Stop();

            base.OnClosing(e);
        }

        /// <summary>
        /// 接收到来自ui的的注销事件，执行具体的注销过程
        /// </summary>
        /// <param name="event"></param>
        [Common.Subscribe]
        public void OnReceiveUILogoutEvent(LogoutEvent @event)
        {
            try
            {
                Service.Contract.ReqLogoutData requestData = new Service.Contract.ReqLogoutData();
                requestData.UserIdentity = UIContext.Current.UserIdentity;

                ServiceProxy.ClientProxyManager.Instance.SendRequest(
                    UIContext.Current.ControlDomainId,
                    UIContext.Current.UserIdentity,
                    Service.Contract.REQUEST_SCENARIO.CONNENT,
                    Service.Contract.REQUEST_COMMAND.CONNECT.LOGOUT,
                    Service.Contract.REQUEST_MODE.SELF,
                    requestData);
            }
            catch (Exception ex)
            {
                Common.Logger.ErrorToTag("UI", "退出登录失败!{0}", ex);
            }
        }

        /// <summary>
        /// 收到来自服务器的注销结果
        /// </summary>
        /// <param name="event"></param>
        [CPPEI.Coolzon.Common.Subscribe]
        public void OnReceiveLogoutEvent(Service.Contract.RespLogoutData @event)
        {
            if (this.Dispatcher.HasShutdownStarted)
            {
                return;
            }
            if (@event.IsSuccess)
            {
                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("注销成功!");

                    // 关闭心跳线程
                    HeartbeatThread.Stop();
                    ReconnectThread.Stop();
                    SwitchMainServerThread.Stop();
                    OpenDefaultSceneThread.Stop();
                    CheckClientStatusThread.Stop();

                    UIContext.Current.Reset();

                    // 显示登录界面
                    CPPEI.Coolzon.UI.Views.LoginView loginView = new UI.Views.LoginView();
                    loginView.Close += loginView_Close;
                    _ctlViewContainer.SwitchView(loginView);
                    loginView.Active();

                    if (_mainView != null)
                    {
                        _ctlViewContainer.Remove(_mainView);
                        _mainView = null;
                    }
                });
            }
            else
            {
                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("注销失败!");
                });
            }
        }

        private HintView hintView;
        /// <summary>
        /// 接收到来自各个模块的信息
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiverMoudleMessageEvent(ModuleMessageEvent @event)
        {
            return;
            this.Dispatcher.Invoke(() =>
            {
                if (hintView == null)
                {
                    hintView = new HintView();
                    hintView.Owner = this;
                    hintView.Show();
                }
                //提示信息窗体位置和父窗体一致
                hintView.Left = this.Left;
                hintView.Top = this.Top + 135;
                //如果窗体最大化时，调整提示信息窗体位置
                if (this.WindowState == System.Windows.WindowState.Maximized)
                {
                    hintView.Left = 0;
                    hintView.Top = 135;
                }
                hintView.SetText(@event.Message);
            });
        }

        /// <summary>
        /// 收到全屏状态改变事件
        /// </summary>
        /// <param name="event"></param>
        [Subscribe]
        public void OnReceiveUIFullscreenStateChangedEvent(UIChangeFullScreenStateEvent @event)
        {
            if (UIContext.Current.IsFullScreen)
            {
                _fullScreenHelper.ExitFullscreen();
                UIContext.Current.IsFullScreen = false;
            }
            else
            {
                _fullScreenHelper.EnterFullscreen();
                UIContext.Current.IsFullScreen = true;
            }
        }

        [Subscribe]
        public void OnReceiveUIEnableInteractiveEvent(UIEnableInteractiveEvent @event)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (_disableInteractiveWindow != null)
                {
                    _disableInteractiveWindow.Release();
                }
            });
        }
        [Subscribe]
        public void OnReceiveUIDisableInteractiveEvent(UIDisableInteractiveEvent @event)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (_disableInteractiveWindow == null)
                {
                    _disableInteractiveWindow = new DisableInteractiveWindow();
                }
                if (this._ctlViewContainer.CurrentView is IMainView)
                {
                    Point point = this._ctlViewContainer.CurrentView.PointToScreen(new Point(0, 0));
                    _disableInteractiveWindow.Left = point.X + this._ctlViewContainer.ActualWidth / 2 - _disableInteractiveWindow.ActualWidth / 2;
                    _disableInteractiveWindow.Top = point.Y + this._ctlViewContainer.ActualHeight / 2 - _disableInteractiveWindow.ActualHeight / 2;
                    _disableInteractiveWindow.Ref(@event.Message, true);
                }
                else
                {
                    _disableInteractiveWindow.Ref(@event.Message, false);
                }
            });
        }

        private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Logger.InfoToTag("MainMouseDown", "MouseDown-{0},X:{1},Y:{2},Left:{3},Middle:{4},Right:{5}", e.OriginalSource.ToString(), e.GetPosition(this).X, e.GetPosition(this).Y, e.LeftButton.ToString(), e.MiddleButton.ToString(), e.RightButton.ToString());
        }

        private void Window_PreviewStylusDown(object sender, StylusDownEventArgs e)
        {
            //Logger.InfoToTag("MainMouseDown", "StylusDown-{0},X:{1},Y:{2}", e.OriginalSource.ToString(), e.GetPosition(this).X, e.GetPosition(this).Y);
        }

        private void Window_PreviewTouchDown(object sender, TouchEventArgs e)
        {
            Logger.InfoToTag("MainMouseDown", "TouchDown");
        }
    }
}
